package com.platform.modules.app.controller;

import com.google.code.kaptcha.Producer;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.JedisUtil;
import com.platform.config.KaptchaConfig;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
@RequestMapping("/app/captcha")
public class AppCaptchaController {

    @Resource
    private Producer producer;
    @Resource
    private JedisUtil jedisUtil;

    /**
     * 验证码
     *
     * @param response response
     * @param uuid     uuid
     */
    @GetMapping("captcha.jpg")
    public void captcha(HttpServletResponse response, String uuid) throws IOException {
        if (StringUtils.isBlank(uuid)) {
            throw new BusinessException("uuid不能为空");
        }
        // 生成文字验证码
        String code = producer.createText();
        // 保存至redis有效期五分钟
        jedisUtil.set(KaptchaConfig.REDIS_KYE+uuid,code,KaptchaConfig.VALID_TIME);
        // 获取图片验证码
        BufferedImage image = producer.createImage(code);
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

}
